package com.heima.comment.service.impl;

import java.util.*;


import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.ApAuthorFeign;
import com.heima.feigns.UserFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.jsoup.nodes.Comment;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    UserFeign userFeign;

    @Autowired
    ApAuthorFeign apAuthorFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    GreenTextScan greenTextScan;
    @Autowired
    CommentHotService commentHotService;

    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        //1. 校验参数
        ApUser user = AppThreadLocalUtils.getUser();
        //校验是否登录
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //校验文章id   校验内容不为空  校验内容长度不能大于140个字符 (validated校验) 注解

        //2. 阿里云校验评论内容是否违规
        //(简单:  此步不做      普通: 阿里云检测有问题提示      高级:  有问题不报异常，替换为**)

        try {
            Map map = greenTextScan.greenTextScan(dto.getContent());
            String suggestion = map.get("suggestion").toString();
            if (suggestion.equals("block")) {
                String minganci = map.get("minganci").toString();
                System.out.println("==============");
                String[] split = minganci.split("_hmtt_");
                for (int i = 1; i < split.length; i++) {
                    String[] split1 = split[i].split("~");
                    dto.setContent(dto.getContent().replace(split1[0], "**"));
                    System.out.println("===========");

                }

                // CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"内容违规");
                // return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW,"内容违规");
            }
        } catch (Exception e) {
            e.printStackTrace();
//            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH,"服务器繁忙");

        }

        //3. 远程查询当前登陆用户信息
        ResponseResult<ApUser> result = userFeign.findUserById(user.getId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }

        ApUser data = result.getData();
        if (data == null) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ResponseResult<ApArticle> apArticleResponseResult = apAuthorFeign.get(dto.getArticleId());
        if (!apArticleResponseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApArticle data1 = apArticleResponseResult.getData();

        //4. 创建评论信息，并保存到mongo
        ApComment apComment = new ApComment();

        apComment.setAuthorId(data.getId());
        apComment.setAuthorName(data.getName());
        apComment.setArticleId(dto.getArticleId());
        apComment.setType((short) 0);
        apComment.setChannelId(data1.getChannelId());
        apComment.setContent(dto.getContent());
        apComment.setImage(data.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short) 0);
        apComment.setOrd((int) System.currentTimeMillis());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        mongoTemplate.insert(apComment);

        return ResponseResult.okResult();

    }

    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */

    @Autowired
    RedissonClient redisson;

    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        //1. 参数校验
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //评论id不能为空  operation必须为 0  或  1
        Map map;
        RLock rlock = redisson.getLock("likes-lock");
        rlock.lock();
        try {
            String commentId = dto.getCommentId();
            ApComment byId = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
            if (byId == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论不存在");
            }

            map = new HashMap<>();
            if (commentId != null) {
                if (dto.getOperation().equals(ApCollection.Type.ARTICLE.getCode())) {
                    Query query = Query.query(Criteria.where("authorId").is(user.getId())
                            .and("commentId").is(byId.getId())
                            .and("operation").is(ApCollection.Type.ARTICLE.getCode()));
                    //2. 根据评论id查询评论数据， 为返回错误信息
                    ApCommentLike one = mongoTemplate.findOne(query, ApCommentLike.class);
                    //3. 如果是点赞操作 判断是否已经点赞
                    if (one != null) {
                        //点过赞提示 请勿重复点赞
                        CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复点赞");
                    }

                    //未点过赞   保存点赞信息到mongo
                    ApCommentLike apCommentLike = new ApCommentLike();
                    apCommentLike.setAuthorId(user.getId());
                    apCommentLike.setCommentId(byId.getId());
                    apCommentLike.setOperation((short) 0);
                    mongoTemplate.insert(apCommentLike);
                    //并修改评论信息的点赞数量( + 1)
                    byId.setLikes(byId.getLikes() + 1);
                    mongoTemplate.save(byId);
                    map.put("likes", byId.getLikes());
                    commentHotService.hotCommentExecutor(byId);

                } else {
                    //4. 如果是取消点赞操作
                    Query query = Query.query(Criteria.where("authorId").is(user.getId())
                            .and("operation").is(ApCollection.Type.ARTICLE.getCode())
                            .and("commentId").is(byId.getId()));
                    //删除点赞信息
                    mongoTemplate.remove(query, ApCommentLike.class);
                    //并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
                    byId.setLikes(byId.getLikes() - 1);
                    if (byId.getLikes() < 0) {
                        CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
                    }

                    mongoTemplate.save(byId);
                    map.put("likes", byId.getLikes());
                }
            }
        }  finally {
            rlock.unlock();
        }
        //5. 返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
        return ResponseResult.okResult(map);
    }

    /**
     * 根据文章id查询评论列表
     *
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {

        //1. 参数校验校验文章id
        if (dto.getSize() == null || dto.getSize() <= 0) {
            dto.setSize(10);
        }
        List<ApComment> apCommentList = null;
        //2. 根据条件查询评论列表
        //(文章id  , 创建时间 小于最小时间 , 截取size条记录 , 创建时间降序)
        // 查询的是热点评论 5条
        if (dto.getIndex().intValue() == 1) {
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("flag").is((short) 1)).limit(5)
                    .with(Sort.by(Sort.Order.desc("likes")));
            apCommentList = mongoTemplate.find(query, ApComment.class);

            // 普通评论
            Query query1 = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("createdTime").lt(dto.getMinDate())
                    .and("flag").is((short) 0));
            query1.with(Sort.by(Sort.Order.desc("createdTime")));
            query1.limit(dto.getSize() - apCommentList.size());
            List<ApComment> list = mongoTemplate.find(query1, ApComment.class);

            apCommentList.addAll(list);

            //3. 判断当前用户是否登录
            ApUser user = AppThreadLocalUtils.getUser();
            if (user == null) {
                //4. 如果未登录直接返回评论列表
                return ResponseResult.okResult(apCommentList);
            }

            //5. 如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
            //(将所有ApComment 转成 ApCommentVO , 点过赞的operation设置为0)
            //5.1 根据当前列表中评论id  和  登录人id 查询评论点赞表，得到点赞数据
            ArrayList<ApCommentVo> apCommentVos = new ArrayList<>();
            for (ApComment apComment : apCommentList) {
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(apComment, apCommentVo);
                Query query2 = Query.query(Criteria.where("commentId").is(apComment.getId())
                        .and("authorId").is(user.getId())
                        .and("operation").is((short) 0));
                ApCommentLike one = mongoTemplate.findOne(query2, ApCommentLike.class);

                if (one != null) {
                    apCommentVo.setOperation((short) 0);
                }
                apCommentVos.add(apCommentVo);
            }
            return ResponseResult.okResult(apCommentVos);
        } else {
            //commentId  in    评论id列表   authorId = 登录人id
            //5.1 根据当前列表中评论id  和  登录人id 查询评论点赞表，得到点赞数据
            //遍历评论列表
            //将每一个评论  ApComment 转成 ApCommentVO
            //其中  如果当前评论id在点赞记录中存在  设置operation字段为0  不存在不用做任何处理
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("createdTime").lt(dto.getMinDate()).and("flag").is((short) 0)
            );
            query.with(Sort.by(Sort.Order.desc("createdTime")));
            query.limit(dto.getSize());
            apCommentList = mongoTemplate.find(query, ApComment.class);
            //判断当前用户是否登录
            ApUser user = AppThreadLocalUtils.getUser();
            if (user == null) {
                //如果未登录直接返回评论列表
                return ResponseResult.okResult(apCommentList);
            }

            //如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
            // (将所有ApComment 转成 ApCommentVO , 点过赞的operation设置为0)
            //5.1 根据当前列表中评论id  和  登录人id 查询评论点赞表，得到点赞数据
            //遍历评论列表
            //将每一个评论  ApComment 转成 ApCommentVO
            //其中  如果当前评论id在点赞记录中存在  设置operation字段为0  不存在不用做任何处理
            List<ApCommentVo> apCommentVos = new ArrayList<>();
            for (ApComment apComment : apCommentList) {
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(apComment, apCommentVo);
                Query query1 = Query.query(Criteria.where("commentId").is(apComment.getId())
                        .and("authorId").is(user.getId())
                        .and("operation").is((short) 0));
                ApCommentLike one = mongoTemplate.findOne(query1, ApCommentLike.class);
                if (one != null) {
                    apCommentVo.setOperation((short) 0);
                }
                apCommentVos.add(apCommentVo);
            }
            return ResponseResult.okResult(apCommentVos);
        }
    }
}